package com.anne.fish.dao.hibernate;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.anne.fish.dao.GenericDao;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>To register this class in your Spring context file, use the following XML.
 * <pre>
 *      &lt;bean id="fooDao" class="com.anne.fish.dao.hibernate.GenericDaoHibernate"&gt;
 *          &lt;constructor-arg value="com.anne.fish.model.Foo"/&gt;
 *      &lt;/bean&gt;
 * </pre>
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
 * @param <T> a type variable
 * @param <PK> the primary key for that type
 */
public class GenericDaoHibernate<T, PK extends Serializable> implements GenericDao<T, PK> {
    /**
     * Log variable for all child classes. Uses LogFactory.getLog(getClass()) from Commons Logging
     */
    protected final Log log = LogFactory.getLog(getClass());
    private Class<T> persistentClass;
    private HibernateTemplate hibernateTemplate;
    private SessionFactory sessionFactory;

    /**
     * Constructor that takes in a class to see which type of entity to persist.
     * Use this constructor when subclassing.
     *
     * @param persistentClass the class type you'd like to persist
     */
    public GenericDaoHibernate(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }

    /**
     * Constructor that takes in a class and sessionFactory for easy creation of DAO.
     *
     * @param persistentClass the class type you'd like to persist
     * @param sessionFactory  the pre-configured Hibernate SessionFactory
     */
    public GenericDaoHibernate(final Class<T> persistentClass, SessionFactory sessionFactory) {
        this.persistentClass = persistentClass;
        this.sessionFactory = sessionFactory;
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    public HibernateTemplate getHibernateTemplate() {
        return this.hibernateTemplate;
    }

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    @Autowired
    @Required
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> getAll() {
        return hibernateTemplate.loadAll(this.persistentClass);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> getAllDistinct() {
        Collection result = new LinkedHashSet(getAll());
        return new ArrayList(result);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public T get(PK id) {
        T entity = (T) hibernateTemplate.get(this.persistentClass, id);

        if (entity == null) {
            log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(this.persistentClass, id);
        }

        return entity;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public boolean exists(PK id) {
        T entity = (T) hibernateTemplate.get(this.persistentClass, id);
        return entity != null;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public T save(T object) {
        return (T) hibernateTemplate.merge(object);
    }

    /**
     * {@inheritDoc}
     */
    public void remove(PK id) {
        hibernateTemplate.delete(this.get(id));
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
        String[] params = new String[queryParams.size()];
        Object[] values = new Object[queryParams.size()];
        
        int index = 0;
        for (String s : queryParams.keySet()) {
            params[index] = s;
            values[index++] = queryParams.get(s);
        }

        return hibernateTemplate.findByNamedQueryAndNamedParam(queryName, params, values);
    }
    
    
    
    //分页相关的查询开始
    
    
    public Integer getSearchCount(String hql) {

		Long count = (Long) getHibernateTemplate().find(hql).listIterator().next();
		return count.intValue();
	}

	public Integer getSearchCount(String hql, Object... args) {
		Long count = (Long) getHibernateTemplate().find(hql, args).listIterator().next();
		return count.intValue();
	}

 
	
	 
	public List<T> findSearch(final String hql, final int pageSize, final int pageNum  ) {
		return findSearch( hql,  pageSize,  pageNum ,  ( Object) null);
	}

 

	@SuppressWarnings("unchecked")
	public List<T> findSearch(final String hql, final int pageSize, final int pageNum , final Object... args) {
		// getHibernateTemplate().setCacheQueries(true);
		Object ob = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if (args != null) {
					for (int i = 0; i < args.length; i++) {
						query.setParameter(i, args[i]);
					}
				}
				query.setFirstResult((pageNum - 1) * pageSize);
				query.setMaxResults(pageSize);
				return query.list();
			}
		});
		return (List) ob;
	}
 
	public List<T> find(final String hql,  final int pageSize, final int pageNum) {
		String entityName = this.persistentClass.getName();

		String countSql = "select count(*) from " + entityName;
		int count = getSearchCount(countSql);
		if (count > 0) {
			return findObjects(hql, pageSize, pageNum ,(Object)null);
		}  

		return null;
	}
	@SuppressWarnings("unchecked")
	public List<T> findObjects(final String hql, final int pageSize, final int pageNum , final Object... args) {
		// getHibernateTemplate().setCacheQueries(true);
		Object ob = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if (args != null) {
					for (int i = 0; i < args.length; i++) {
						query.setParameter(i, args[i]);
					}
				}
				query.setFirstResult((pageNum - 1) * pageSize);
				query.setMaxResults(pageSize);
				return query.list();
			}
		});
		return (List) ob;
	}
	
	
	@SuppressWarnings("unchecked")
	public int updateOrDelete(final String hql, final Object[] args) {
		// getHibernateTemplate().setCacheQueries(true);
		Object ob = this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query q = session.createQuery(hql);
				if (args != null) {
					for (int i = 0; i < args.length; i++) {
						q.setParameter(i, args[i]);
					}
				}
				int i = q.executeUpdate();
				return i;
			}
		});
		return (Integer) ob;
	}

	public int updateOrDelete(final String hql, final Object arg) {
		Object[] args = { arg };
		return updateOrDelete(hql, args);
	}
}
